package cn.edu.zstu.qingzhu.qingzhushop.handler;

import cn.edu.zstu.qingzhu.qingzhushop.entity.ResponseBean;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author ShenTuZhiGang
 * @Version 1.0.0
 * @Date 2020-03-21 16:51
 */
@Component
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        ResponseBean retTemp = ResponseBean.success("登录成功");
        retTemp.setData(authentication.getPrincipal());
        PrintWriter out = httpServletResponse.getWriter();
        out.write(new ObjectMapper().writeValueAsString(retTemp));
        out.flush();
        out.close();
    }
}
